package hrc.wow_notifier;

import hrc.wow_notifier.service.NotifyService;
import hrc.wow_notifier.service.NotifyServiceFactory;

import java.util.Calendar;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;


public class WOWNotifier extends Activity  {
	private int position;
	private NotifyService notifyService;
	private boolean alarmFlag;
	private ProgressDialog dialog;
	private PendingIntent pi;
	private AlarmManager alarmManager;
	
	//widget
	private Spinner localSpinner;
	private AutoCompleteTextView serverNameSpinner;
	private CheckBox notifyCheckBox;
	private Button submitButton;
	private TextView statusTextView;
	
	
	
	
	private Handler handler = new Handler() {
		
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.arg1 == 1) {
				msg.arg1=0;
				dialog.cancel();
			}
		}

	};
	private Runnable getStatusRunner = new Runnable() {

		@Override
		public void run() {
			/*TextView serverNameTextView = (TextView) serverNameSpinner
					.getSelectedView();
			String serverName = serverNameTextView.getText().toString();*/
			String serverName= serverNameSpinner.getText().toString();
			boolean online = notifyService.isServerOnline(serverName);
			String status = online ? "在线" : "离线";
			if (alarmFlag) {
				setAlarm(serverName, online);
			}
			String result = String.format("服务器  %s 目前的状态是 %s", serverName,
					status);
			statusTextView.setText(result);
			// send message
			Message message = new Message();
			message.arg1 = 1;
			handler.sendMessage(message);
		}
	};
	private OnItemSelectedListener localSpinnerListener = new OnItemSelectedListener() {

		@Override
		public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			// get notifyService instance
			position = localSpinner.getSelectedItemPosition();
			notifyService = NotifyServiceFactory.createNotifyService(position);
			// bind the servers' name to serverNameSpinner
			ArrayAdapter<String> serverNameAdapter = new ArrayAdapter<String>(
					WOWNotifier.this,
					android.R.layout.simple_dropdown_item_1line,
					notifyService.loadServerName());
			serverNameSpinner.setAdapter(serverNameAdapter);
			serverNameSpinner.setClickable(true);
			// only after the location selected can you use the submit button
			submitButton.setOnClickListener(commitClickListener);
			// only after the location selected can you use the notify service
			notifyCheckBox.setOnCheckedChangeListener(checkedChangeListener);
		}

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {

		}
	};

	private OnClickListener commitClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			dialog = ProgressDialog.show(WOWNotifier.this, "", getResources()
					.getString(R.string.interacting));
			handler.post(getStatusRunner);
		}
	};

	private OnCheckedChangeListener checkedChangeListener = new OnCheckedChangeListener() {

		@Override
		public void onCheckedChanged(CompoundButton buttonView,
				boolean isChecked) {
			if (isChecked) {
				Toast toast = Toast.makeText(WOWNotifier.this, getResources()
						.getString(R.string.notify_tip), Toast.LENGTH_LONG);
				toast.show();
				alarmFlag = true;
			} else {
				alarmFlag = false;
				alarmManager.cancel(pi);
			}

		}
	};

	private void setAlarm(String serverName, boolean online) {
		final String ACTION = "hrc.wow_notifier.AlarmReceiver";
		Intent intent = new Intent();
		intent.setAction(ACTION);
		intent.putExtra("serverName", serverName);
		intent.putExtra("mode", position);
		intent.putExtra("online", online);

		 pi = PendingIntent.getBroadcast(
				getApplicationContext(), 0, intent, 0);

		alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
		Calendar c = Calendar.getInstance();
		long triggerTime = c.getTimeInMillis() + 1800000;
		alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
				triggerTime, AlarmManager.INTERVAL_HOUR, pi);
		
	}

	@Override
	protected void onResume() {
		Intent intent = getIntent();
		boolean shoke = intent.getBooleanExtra("shoke", false);
		if (shoke) {
			intent.putExtra("shoke", false);
			vibrate();
			Toast toast=Toast.makeText(WOWNotifier.this, getResources().getString(R.string.status_online), Toast.LENGTH_LONG);
			toast.show();
		}
		super.onResume();
	}

	private void vibrate() {
		Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
		long[] pattern = { 800, 50, 400, 30 }; 
		vibrator.vibrate(pattern, 2);
	}

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.main);
		// init widgets
		localSpinner = (Spinner) findViewById(R.id.server_local);
		serverNameSpinner = (AutoCompleteTextView) findViewById(R.id.service_name);
		notifyCheckBox = (CheckBox) findViewById(R.id.notify);
		submitButton = (Button) findViewById(R.id.commit);
		statusTextView = (TextView) findViewById(R.id.status);
		
		// bind data to localSpinner
		String[] local = getResources().getStringArray(R.array.locals);
		ArrayAdapter<String> localAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_dropdown_item_1line, local);
		localSpinner.setAdapter(localAdapter);
		localSpinner.setOnItemSelectedListener(localSpinnerListener);
	}

	
}